(function ($) {
    var urls = {
        postUrl: "/app/api/ledger/toOne",
        saveUrl: "/app/api/ledger/add"
    };

    var defaults = {
        server: "${ctx}",
        keyCode: "form_template",
        title: "台账展示设置",
        width: 550,
        template: '<div style="display: none"><div style="max-height: 500px"><form><input type="hidden" name="id" />' +
        '<ul></ul></form></div></div>'
    };

    function FormPanel(opt) {
        this.options = opt;
        var w = $(this.options.template).appendTo("body");
        this.panel = w.children();
        this.form = this.panel.find("form");
        this.form.attr("action", this.options.server + urls.saveUrl);
        this.complete = true;
        var that = this;
        this.htmlTemplete = '<li style="padding-top: 2px;height:30px;line-height:30px;border-bottom: 1px solid #00b7ee;">' +
            '<label class="ml10">表头：</label>' +
            '<input type="text" class="name hydra-input-width"  value="{{name}}" /></span> &nbsp; &nbsp;' +
            '<label class="ml10">顺序：</label><input  class="easyui-numberbox sort" value="{{sort}}" style="width: 50px"/>' +
            '<label class="ml10">宽度：</label><input  class="easyui-numberbox width"  value="{{width}}" style="width: 50px"/>' +
            '<label style="display: none"><input type="text" class="field" value="{{field}}" /></label>' +
            '<label style="display: none"><input type="text" class="enum" value="{{enums}}" /></label>' +
            '<label class="ml10">显示：</label>{{#show}}<input type="checkbox" class="check" checked="checked"/>{{/show}}' +
            '{{^show}}<input type="checkbox" class="check" />{{/show}}</li>';
        that.initData();
        that.initDialog();
    }

    FormPanel.prototype.initData = function () {
        var that = this;
        $.ajax({
            type: "post",
            url: this.options.server + urls.postUrl,
            data: "keycode=" + this.options.keyCode,
            dataType: "json",
            async: false,
            success: function (json) {
                var rows = json.userTemplet.split(";");
                that.panel.find("input").val(json.id);
                var result = [];
                $.each(rows, function (i, item) {
                    var values = item.split("=");
                    result.push(Mustache.render(that.htmlTemplete,
                        {
                            sort: values[0],
                            field: values[1],
                            name: values[2],
                            width: values[3],
                            show: values[4] == "true",
                            enums: values.length > 5 ? values[5] : null
                        }));
                });
                that.panel.find("ul").html(result.join(""));
                that.panel.find("input.easyui-numberbox").numberbox();
            }
        });
    };
    FormPanel.prototype.initDialog = function () {
        var that = this;
        that.panel.dialog({
            width: that.options.width,
            height: that.options.height,
            closed: true,
            fit: false,
            modal: true,
            title: that.options.title,
            loadingMessage: '正在加载……',
            buttons: [
                {
                    text: '保存',
                    handler: function () {
                        that.panel.wait("start", "保存中,请稍候.");
                        var postData = that.form.serializeJson();
                        var lis = that.form.find("li");
                        var data = "";
                        $.each(lis, function (i, li) {
                            data += $(li).find("input.sort").val() + "=" + $(li).find("input.field").val() + "=" +
                                $(li).find("input.name").val() + "=" + $(li).find("input.width").val() + "=" +
                                $(li).find("input.check").is(":checked");
                            var enumStr = $(li).find("input.enum").val();
                            if (enumStr != null && enumStr != "") {
                                data += "=" + enumStr + ";";
                            } else {
                                data += ";";
                            }
                        });
                        postData.userTemplet = data.substring(0, data.length - 1);
                        $.post(that.form.attr("action"), $.utils.buildJson(postData), function () {
                            that.panel.wait("end");
                            $.messager.alert('信息', '保存成功', 'info');
                            that.panel.dialog("close");
                        })
                    }
                },
                {
                    text: '取消',
                    handler: function () {
                        that.initData();
                        that.initDialog();
                        that.panel.dialog("close");
                    }
                }
            ]
        });
    };
    FormPanel.prototype.open = function () {
        this.complete = true;
        this.panel.dialog("open");
    };

    FormPanel.prototype.close = function () {
        this.panel.dialog("close");
    };

    FormPanel.prototype.destroy = function () {
        this.panel.dialog("destroy");
        this.panel.remove();
    };

    var panelCache = {};

    $.AutoForm = {
        getFormPanel: function (keycode, opt) {
            if (!panelCache[keycode]) {
                panelCache[keycode] = new FormPanel($.extend({}, defaults, opt, {keyCode: keycode}));
            }
            return panelCache[keycode];
        }
    };
})(jQuery);